package Chapter3;

public final class MyStringBuffer implements java.io.Serializable {
    private char[] value;
    private int n;

    public MyStringBuffer(int capacity){
        this.value=new char[capacity];
        this.n=0;
    }

    public MyStringBuffer(){
        this(16);
    }

    public MyStringBuffer(String s){
        this(s.length()+16);
        this.n=s.length();
        for (int i=0;i<this.n;i++)
            this.value[i]=s.charAt(i);
    }

    public int length(){
        return this.n;
    }

    public int capacity(){
        return this.value.length;
    }

    public synchronized String toString(){
        return new String(this.value,0,this.n);
    }

    //有问题，待改进
    public synchronized char charAt(int i){
            return this.value[i];
    }

    public void setCharAt(int i,char ch){}

    public synchronized MyStringBuffer insert(int i,String s){
        if (this.n==0&&i==0||this.n>0&&i>=0&&i<this.n){
            if (s==null)
                s="";
            char[] temp=this.value;
            if (this.value.length<this.n+s.length()){
                this.value=new char[(this.value.length+s.length())*2];
                for (int j=0;j<i;j++)
                    this.value[j]=temp[j];
            }
            for (int j=this.n-1;j>=i;j--)
                this.value[j+s.length()]=temp[j];
            for (int j=0;j<s.length();j++)
                this.value[i+j]=s.charAt(j);
            this.n+=s.length();
            return this;
        }else
            throw new StringIndexOutOfBoundsException("i="+i);
    }

//    public synchronized MyStringBuffer insert(int i,MyStringBuffer sbuf){}

    public synchronized MyStringBuffer insert(int i,boolean b){
        return this.insert(i,b?"true":"false");
    }

    public synchronized MyStringBuffer append(String s){
        return this.insert(this.n,s);
    }

    public synchronized MyStringBuffer delete(int begin,int end){
        if (begin>=0&&begin<this.n&&end>=0&&begin<=end){
            if (end>this.n)
                end=this.n;
            for (int i=0;i<this.n-end;i++)
                this.value[begin+i]=this.value[end+i];
            this.n-=end-begin;
            return this;
        }else
            throw new StringIndexOutOfBoundsException("begin="+begin+",end="+end+",end-begin="+(end-begin));
    }
}
